<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="beautifulsoup,xpath,正则表达式,">










<meta name="description" content="网络爬虫之数据提取数据提取的解析器有lxml、Beautifulsoup和正则表达式三种，对比如下：    解析工具 解析速度 使用难度     lxml 快 简单   BeautifulSoup 最慢 最简单   正则表达式 最快 最难">
<meta name="keywords" content="beautifulsoup,xpath,正则表达式">
<meta property="og:type" content="article">
<meta property="og:title" content="Python爬虫（2）">
<meta property="og:url" content="http://Anzusen.com/2019/06/09/Python爬虫（2）/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="网络爬虫之数据提取数据提取的解析器有lxml、Beautifulsoup和正则表达式三种，对比如下：    解析工具 解析速度 使用难度     lxml 快 简单   BeautifulSoup 最慢 最简单   正则表达式 最快 最难">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/image/xpath_note.png">
<meta property="og:image" content="http://anzusen.com/image/xpath_weiyu.png">
<meta property="og:image" content="http://anzusen.com/image/xpath_tongpeifu.png">
<meta property="og:image" content="http://anzusen.com/image/jixiqi.png">
<meta property="og:updated_time" content="2020-04-06T13:26:42.454Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python爬虫（2）">
<meta name="twitter:description" content="网络爬虫之数据提取数据提取的解析器有lxml、Beautifulsoup和正则表达式三种，对比如下：    解析工具 解析速度 使用难度     lxml 快 简单   BeautifulSoup 最慢 最简单   正则表达式 最快 最难">
<meta name="twitter:image" content="http://anzusen.com/image/xpath_note.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2019/06/09/Python爬虫（2）/">





  <title>Python爬虫（2） | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2019/06/09/Python爬虫（2）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python爬虫（2）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-06-09T15:13:41+08:00">
                2019-06-09
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python爬虫/" itemprop="url" rel="index">
                    <span itemprop="name">Python爬虫</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/06/09/Python爬虫（2）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/06/09/Python爬虫（2）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.3k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  14
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="网络爬虫之数据提取"><a href="#网络爬虫之数据提取" class="headerlink" title="网络爬虫之数据提取"></a>网络爬虫之数据提取</h1><p>数据提取的解析器有lxml、Beautifulsoup和正则表达式三种，对比如下：</p>
<table>
<thead>
<tr>
<th style="text-align:left">解析工具</th>
<th style="text-align:left">解析速度</th>
<th style="text-align:left">使用难度</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">lxml</td>
<td style="text-align:left">快</td>
<td style="text-align:left">简单</td>
</tr>
<tr>
<td style="text-align:left">BeautifulSoup</td>
<td style="text-align:left">最慢</td>
<td style="text-align:left">最简单</td>
</tr>
<tr>
<td style="text-align:left">正则表达式</td>
<td style="text-align:left">最快</td>
<td style="text-align:left">最难</td>
</tr>
</tbody>
</table>
<a id="more"></a>
<h2 id="Xpath"><a href="#Xpath" class="headerlink" title="Xpath"></a>Xpath</h2><p>  xpath (XML Path Language)是- -门 ]在XML和HTML文档中查找信息的语信，可用来在XML和HTML文档中对元素和属性进行遍历。</p>
<h3 id="XPath开发工具"><a href="#XPath开发工具" class="headerlink" title="XPath开发工具"></a>XPath开发工具</h3><ol>
<li>Chrome插件XPath Helper。</li>
<li>Firefox插件XPath Checker。<h3 id="xpath语法"><a href="#xpath语法" class="headerlink" title="xpath语法"></a>xpath语法</h3><img src="/image/xpath_note.png" alt></li>
</ol>
<p><img src="/image/xpath_weiyu.png" alt></p>
<p><img src="/image/xpath_tongpeifu.png" alt></p>
<h3 id="使用方式："><a href="#使用方式：" class="headerlink" title="使用方式："></a>使用方式：</h3><p>使用//获取整个页面当中的元素，然后写标签名，然后再写谓词进行提取。比如：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">//div[@class=&apos;abc&apos;]</span><br></pre></td></tr></table></figure></p>
<h4 id="需要注意的知识点："><a href="#需要注意的知识点：" class="headerlink" title="需要注意的知识点："></a>需要注意的知识点：</h4><ol>
<li>/和//的区别：/代表只获取直接子节点。//获取子孙节点。一般//用得比较多。当然也要视情况而定。</li>
<li><p>contains：有时候某个属性中包含了多个值，那么可以使用<code>contains</code>函数。示例代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">//div[contains(@class,&apos;job_detail&apos;)]</span><br></pre></td></tr></table></figure>
</li>
<li><p>谓词中的下标是从1开始的，不是从0开始的。</p>
</li>
</ol>
<h2 id="lxml解析器解析HTML代码"><a href="#lxml解析器解析HTML代码" class="headerlink" title="lxml解析器解析HTML代码"></a>lxml解析器解析HTML代码</h2><h3 id="安装lxml"><a href="#安装lxml" class="headerlink" title="安装lxml"></a>安装lxml</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install lxml</span><br></pre></td></tr></table></figure>
<h3 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h3><ol>
<li><p>解析html字符串：使用<code>lxml.etree.HTML</code>进行解析。示例代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> lxml <span class="keyword">import</span> etree</span><br><span class="line"></span><br><span class="line">htmlElement = etree.HTML(text)</span><br><span class="line">print(etree.tostring(htmlElement,encoding=<span class="string">'utf-8'</span>).decode(<span class="string">"utf-8"</span>))</span><br></pre></td></tr></table></figure>
</li>
<li><p>解析html文件：使用<code>lxml.etree.parse</code>进行解析。示例代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">htmlElement = etree.parse(<span class="string">"tencent.html"</span>)</span><br><span class="line">print(etree.tostring(htmlElement, encoding=<span class="string">'utf-8'</span>).decode(<span class="string">'utf-8'</span>))</span><br></pre></td></tr></table></figure>
<p>这个函数默认使用的是XML解析器，所以如果碰到一些不规范的HTML代码的时候就会解析错误，这时候就要自己创建HTML解析器。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">parser = etree.HTMLParser(encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">htmlElement = etree.parse(<span class="string">"lagou.html"</span>,parser=parser)</span><br><span class="line">print(etree.tostring(htmlElement, encoding=<span class="string">'utf-8'</span>).decode(<span class="string">'utf-8'</span>))</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="lxml结合xpath"><a href="#lxml结合xpath" class="headerlink" title="lxml结合xpath"></a>lxml结合xpath</h2><ol>
<li>使用<code>xpath</code>语法。应该使用<code>Element.xpath</code>方法。来执行xpath的选择。示例代码如下：<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">trs = html.xpath(<span class="string">"//tr[position()&gt;1]"</span>)</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><code>xpath函数</code>返回来的永远是一个列表。</p>
<ol start="2">
<li><p>获取某个标签的属性：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">href = html.xpath(<span class="string">"//a/@href"</span>)</span><br><span class="line"><span class="comment"># 获取a标签的href属性对应的值</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>获取文本，是通过<code>xpath</code>中的<code>text()</code>函数。示例代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">address = tr.xpath(<span class="string">"./td[4]/text()"</span>)[<span class="number">0</span>]</span><br></pre></td></tr></table></figure>
</li>
<li><p>在某个标签下，再执行xpath函数，获取这个标签下的子孙元素，那么应该在斜杠之前加一个点，代表是在当前元素下获取。示例代码如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">address = tr.xpath(<span class="string">"./td[4]/text()"</span>)[<span class="number">0</span>]</span><br></pre></td></tr></table></figure>
</li>
<li><p>综合示例如下：</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"><span class="keyword">from</span> lxml <span class="keyword">import</span> etree</span><br><span class="line"></span><br><span class="line">parser = etree.HTMLParser(encoding=<span class="string">'utf-8'</span>)</span><br><span class="line">html = etree.parse(<span class="string">"tencent.html"</span>,parser=parser)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 1. 获取所有tr标签</span></span><br><span class="line"><span class="comment"># //tr</span></span><br><span class="line"><span class="comment"># xpath函数返回的是一个列表</span></span><br><span class="line">trs = html.xpath(<span class="string">"//tr"</span>)</span><br><span class="line"><span class="keyword">for</span> tr <span class="keyword">in</span> trs:</span><br><span class="line">    print(etree.tostring(tr,encoding=<span class="string">'utf-8'</span>).decode(<span class="string">"utf-8"</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 2. 获取第2个tr标签</span></span><br><span class="line">tr = html.xpath(<span class="string">"//tr[2]"</span>)[<span class="number">0</span>]</span><br><span class="line">print(etree.tostring(tr,encoding=<span class="string">'utf-8'</span>).decode(<span class="string">"utf-8"</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 3. 获取所有class等于even的tr标签</span></span><br><span class="line">trs = html.xpath(<span class="string">"//tr[@class='even']"</span>)</span><br><span class="line"><span class="keyword">for</span> tr <span class="keyword">in</span> trs:</span><br><span class="line">    print(etree.tostring(tr,encoding=<span class="string">'utf-8'</span>).decode(<span class="string">"utf-8"</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 4. 获取所有a标签的href属性</span></span><br><span class="line">aList = html.xpath(<span class="string">"//a/@href"</span>)</span><br><span class="line"><span class="keyword">for</span> a <span class="keyword">in</span> aList:</span><br><span class="line">    print(<span class="string">"http://hr.tencent.com/"</span>+a)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 5. 获取所有的职位信息（纯文本）</span></span><br><span class="line">trs = html.xpath(<span class="string">"//tr[position()&gt;1]"</span>)</span><br><span class="line">positions = []</span><br><span class="line"><span class="keyword">for</span> tr <span class="keyword">in</span> trs:</span><br><span class="line">    <span class="comment"># 在某个标签下，再执行xpath函数，获取这个标签下的子孙元素</span></span><br><span class="line">    <span class="comment"># 那么应该在//之前加一个点，代表是在当前元素下获取</span></span><br><span class="line">    href = tr.xpath(<span class="string">".//a/@href"</span>)[<span class="number">0</span>]</span><br><span class="line">    fullurl = <span class="string">'http://hr.tencent.com/'</span> + href</span><br><span class="line">    title = tr.xpath(<span class="string">"./td[1]//text()"</span>)[<span class="number">0</span>]</span><br><span class="line">    category = tr.xpath(<span class="string">"./td[2]/text()"</span>)[<span class="number">0</span>]</span><br><span class="line">    nums = tr.xpath(<span class="string">"./td[3]/text()"</span>)[<span class="number">0</span>]</span><br><span class="line">    address = tr.xpath(<span class="string">"./td[4]/text()"</span>)[<span class="number">0</span>]</span><br><span class="line">    pubtime = tr.xpath(<span class="string">"./td[5]/text()"</span>)[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">    position = &#123;</span><br><span class="line">        <span class="string">'url'</span>: fullurl,</span><br><span class="line">        <span class="string">'title'</span>: title,</span><br><span class="line">        <span class="string">'category'</span>: category,</span><br><span class="line">        <span class="string">'nums'</span>: nums,</span><br><span class="line">        <span class="string">'address'</span>: address,</span><br><span class="line">        <span class="string">'pubtime'</span>: pubtime</span><br><span class="line">    &#125;</span><br><span class="line">    positions.append(position)</span><br><span class="line"></span><br><span class="line">print(positions)</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>下面是两个实战例子，爬取豆瓣电影top250网页内容和爬取电影天堂近期电影网页内容，已上传到码云，地址如下。</li>
</ol>
<h2 id="BeautifulSoup"><a href="#BeautifulSoup" class="headerlink" title="BeautifulSoup"></a>BeautifulSoup</h2><h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip install bs4</span><br></pre></td></tr></table></figure>
<p>用BeautifulSoup解析的时候需要指定一些解析器，一些常用的解析器：<br><img src="/image/jixiqi.png" alt="解析器"></p>
<p>各种解析器的优势和劣势在图中可以很明显看出，这里多说一句：html5lib是一个类似浏览器的解析器，功能很强大，如果遇到那些很古怪的网页代码就可以考虑用这个解析器，直接用命令：pip install html5lib 安装即可。</p>
<h3 id="使用-1"><a href="#使用-1" class="headerlink" title="使用"></a>使用</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">#encoding: utf-8</span><br><span class="line"></span><br><span class="line">from bs4 import BeautifulSoup</span><br><span class="line"></span><br><span class="line">html = &quot;&quot;&quot;</span><br><span class="line">这里省略htmL格式字符串内容，你可以自己去网站审查元素复制过来</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line"># pip install lxml 安装lxml解析器</span><br><span class="line">bs = BeautifulSoup(html,&quot;lxml&quot;)</span><br><span class="line">print(bs.prettify()) # 美化</span><br></pre></td></tr></table></figure>
<h4 id="find-all与find"><a href="#find-all与find" class="headerlink" title="find_all与find"></a>find_all与find</h4><h5 id="find-all的使用："><a href="#find-all的使用：" class="headerlink" title="find_all的使用："></a>find_all的使用：</h5><ol>
<li>在提取标签的时候，第一个参数是标签的名字。然后如果在提取标签的时候想要使用标签属性进行过滤，那么可以在这个方法中通过关键字参数的形式，将属性的名字以及对应的值传进去。或者是使用<code>attrs</code>属性，将所有的属性以及对应的值放在一个字典中传给<code>attrs</code>属性。</li>
<li>有些时候，在提取标签的时候，不想提取那么多，那么可以使用<code>limit</code>参数。限制提取多少个。</li>
</ol>
<h5 id="find与find-all的区别："><a href="#find与find-all的区别：" class="headerlink" title="find与find_all的区别："></a>find与find_all的区别：</h5><ol>
<li>find：找到第一个满足条件的标签就返回。说白了，就是只会返回一个元素。</li>
<li>find_all:将所有满足条件的标签都返回。说白了，会返回很多标签（以列表的形式）。</li>
</ol>
<h5 id="使用find和find-all的过滤条件："><a href="#使用find和find-all的过滤条件：" class="headerlink" title="使用find和find_all的过滤条件："></a>使用find和find_all的过滤条件：</h5><ol>
<li>关键字参数：将属性的名字作为关键字参数的名字，以及属性的值作为关键字参数的值进行过滤。</li>
<li>attrs参数：将属性条件放到一个字典中，传给attrs参数。</li>
</ol>
<h4 id="获取标签的属性："><a href="#获取标签的属性：" class="headerlink" title="获取标签的属性："></a>获取标签的属性：</h4><ol>
<li><p>通过下标获取：通过标签的下标的方式。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">href = a[<span class="string">'href'</span>]</span><br></pre></td></tr></table></figure>
</li>
<li><p>通过attrs属性获取：示例代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">href = a.attrs[<span class="string">'href'</span>]</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h4 id="string和strings、stripped-strings属性以及get-text方法："><a href="#string和strings、stripped-strings属性以及get-text方法：" class="headerlink" title="string和strings、stripped_strings属性以及get_text方法："></a>string和strings、stripped_strings属性以及get_text方法：</h4><ol>
<li>string：获取某个标签下的非标签字符串（他自己的）。返回来的是个字符串。如果这个标签下有多行字符，那么就不能获取到了。</li>
<li>strings：获取某个标签下的子孙非标签字符串。返回来的是个生成器。</li>
<li>stripped_strings：获取某个标签下的子孙非标签字符串，会去掉空白字符。返回来的是个生成器。</li>
<li>get_text：获取某个标签下的子孙非标签字符串。不是以列表的形式返回，是以普通字符串返回。</li>
</ol>
<h3 id="综合示例"><a href="#综合示例" class="headerlink" title="综合示例"></a>综合示例</h3><p>代码如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> bs4 <span class="keyword">import</span> BeautifulSoup</span><br><span class="line"></span><br><span class="line">html = <span class="string">"""省略 """</span></span><br><span class="line">soup = BeautifulSoup(html,<span class="string">'lxml'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 1. 获取所有tr标签</span></span><br><span class="line">trs = soup.find_all(<span class="string">'tr'</span>)</span><br><span class="line"><span class="keyword">for</span> tr <span class="keyword">in</span> trs:</span><br><span class="line">    print(tr)</span><br><span class="line">    print(<span class="string">'='</span>*<span class="number">30</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 2. 获取第2个tr标签</span></span><br><span class="line">tr = soup.find_all(<span class="string">'tr'</span>,limit=<span class="number">2</span>)[<span class="number">1</span>]第二个参数limit用来限制获取的数量，防止太多</span><br><span class="line">print(tr)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 3. 获取所有class等于even的tr标签</span></span><br><span class="line">trs = soup.find_all(<span class="string">'tr'</span>,   class_ = <span class="string">"even"</span>)</span><br><span class="line"><span class="comment"># trs = soup.find_all('tr',attrs=&#123;'class':"even"&#125;)# atrribute属性</span></span><br><span class="line"><span class="keyword">for</span> tr <span class="keyword">in</span> trs:</span><br><span class="line">    print(tr)</span><br><span class="line">    print(<span class="string">'='</span>*<span class="number">30</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 4. 将所有id等于test，class也等于test的a标签提取出来。</span></span><br><span class="line"><span class="comment"># aList = soup.find_all('a',id='test',class_='test')</span></span><br><span class="line">aList = soup.find_all(<span class="string">'a'</span>,attrs=&#123;<span class="string">"id"</span>:<span class="string">"test"</span>,<span class="string">"class"</span>:<span class="string">"test"</span>&#125;)</span><br><span class="line"><span class="keyword">for</span> a <span class="keyword">in</span> aList:</span><br><span class="line">    print(a)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 5. 获取所有a标签的href属性</span></span><br><span class="line">aList = soup.find_all(<span class="string">'a'</span>)</span><br><span class="line"><span class="keyword">for</span> a <span class="keyword">in</span> aList:</span><br><span class="line">    <span class="comment"># 1. 通过下标操作的方式</span></span><br><span class="line">    <span class="comment"># href = a['href']</span></span><br><span class="line">    <span class="comment"># print(href)</span></span><br><span class="line">    <span class="comment"># 2. 通过attrs属性的方式</span></span><br><span class="line">    href = a.attrs[<span class="string">'href'</span>]</span><br><span class="line">    print(href)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 6. 获取所有的职位信息（纯文本）</span></span><br><span class="line">trs = soup.find_all(<span class="string">'tr'</span>)[<span class="number">1</span>:] <span class="comment">#第0个tr标签不需要</span></span><br><span class="line">movies = []</span><br><span class="line"><span class="keyword">for</span> tr <span class="keyword">in</span> trs:</span><br><span class="line">    movie = &#123;&#125;</span><br><span class="line"><span class="comment"># 方式1</span></span><br><span class="line">    <span class="comment"># tds = tr.find_all("td")</span></span><br><span class="line">    <span class="comment"># title = tds[0].string # 去掉多余的标签</span></span><br><span class="line">    <span class="comment"># category = tds[1].string</span></span><br><span class="line">    <span class="comment"># nums = tds[2].string</span></span><br><span class="line">    <span class="comment"># city = tds[3].string</span></span><br><span class="line">    <span class="comment"># pubtime = tds[4].string</span></span><br><span class="line">    <span class="comment"># movie['title'] = title</span></span><br><span class="line">    <span class="comment"># movie['category'] = category</span></span><br><span class="line">    <span class="comment"># movie['nums'] = nums</span></span><br><span class="line">    <span class="comment"># movie['city'] = city</span></span><br><span class="line">    <span class="comment"># movie['pubtime'] = pubtime</span></span><br><span class="line">    <span class="comment"># movies.append(movie)</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 方式2</span></span><br><span class="line">	<span class="comment">#2.1</span></span><br><span class="line">    infos = list(tr.strings) <span class="comment">#这种方法换行符等空白字符也会被提取出来</span></span><br><span class="line">    print(infos)</span><br><span class="line">    <span class="comment">#2.2</span></span><br><span class="line">    infos = list(tr.stripped_strings)<span class="comment">#stripp可以过滤空白字符</span></span><br><span class="line">    movie[<span class="string">'title'</span>] = infos[<span class="number">0</span>]</span><br><span class="line">    movie[<span class="string">'category'</span>] = infos[<span class="number">1</span>]</span><br><span class="line">    movie[<span class="string">'nums'</span>] = infos[<span class="number">2</span>]</span><br><span class="line">    movie[<span class="string">'city'</span>] = infos[<span class="number">3</span>]</span><br><span class="line">    movie[<span class="string">'pubtime'</span>] = infos[<span class="number">4</span>]</span><br><span class="line">    movies.append(movie)</span><br><span class="line"></span><br><span class="line">print(movies)</span><br></pre></td></tr></table></figure></p>
<p>有关匿名函数（lambda表达式）和map函数的用法。<br><a href="https://www.runoob.com/python/python-func-map.html" target="_blank" rel="noopener">map函数</a><br><a href="https://www.runoob.com/python/python-functions.html" target="_blank" rel="noopener">lambda表达式</a></p>
<h2 id="正则表达式"><a href="#正则表达式" class="headerlink" title="正则表达式"></a>正则表达式</h2><h3 id="匹配规则"><a href="#匹配规则" class="headerlink" title="匹配规则"></a>匹配规则</h3><h4 id="特殊匹配字符"><a href="#特殊匹配字符" class="headerlink" title="特殊匹配字符"></a>特殊匹配字符</h4><ol>
<li>匹配一个字符</li>
</ol>
<ul>
<li>‘字符串’:匹配某个字符串。</li>
<li>点：匹配任意的字符。但是不能匹配\n，可以添加参数：re.DOTALL解决</li>
<li>\d：匹配任意的数字（0-9）。</li>
<li>\D：匹配任意的非数字。</li>
<li>\s：匹配空白字符（\n，\t，\r，空格）\r回车。</li>
<li>\w：匹配的是a-z,A-Z,数字和下划线。</li>
<li>\W：与\w相反。</li>
<li>[]组合的方式，只要满足中括号中的字符，就可以匹配， 中括号的形式代替\d：[0-9]；中括号的形式代替\D：[^0-9]；中括号的形式代替\w：[a-zA-Z0-9_]；中括号的形式代替\W：[^a-zA-Z0-9_]</li>
</ul>
<ol start="2">
<li>匹配多个字符</li>
</ol>
<ul>
<li>*：可以匹配0或者任意多个字符</li>
<li>+：匹配1个或者多个字符 ， 如果第一个不是，就返回错误</li>
<li>?：匹配一个或者0个（要么没有，要么就只有一个）</li>
<li>{m}：匹配m个字符。</li>
<li>{m,n}：匹配m-n个字符 ，匹配到最多的字符（不超过n）返回</li>
</ul>
<ol start="3">
<li>小案例<br>3.1. 验证手机号码：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"12578900980"</span> <span class="comment"># 以1开头，第二位是34578中的一位，后面九个字符任意</span></span><br><span class="line">ret = re.match(<span class="string">'1[34578]\d&#123;9&#125;'</span>,text)</span><br><span class="line">print(ret.group())</span><br></pre></td></tr></table></figure>
<p>3.2. 验证邮箱：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"hynever12_@163com"</span></span><br><span class="line">ret = re.match(<span class="string">'\w+@[a-z0-9]+\.[a-z]+'</span>,text) <span class="comment"># 任意数字字母下划线+@+数字或字母（163、qq）+.+字母（com、net）</span></span><br><span class="line">print(ret.group())</span><br></pre></td></tr></table></figure>
<p>3.3.  验证URL</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"https://baike.baidu.com/item/Python/407313?fr=aladdin"</span></span><br><span class="line">ret = re.match(<span class="string">'(http|https|ftp)://[^\s]+'</span>,text)</span><br><span class="line">print(ret.group())</span><br></pre></td></tr></table></figure>
<p>3.4.  验证身份证：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"31131118908123230a"</span></span><br><span class="line">ret = re.match(<span class="string">'\d&#123;17&#125;[\dxX]'</span>,text)</span><br><span class="line">print(ret.group())</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>特殊字符</li>
</ol>
<ul>
<li>^（脱字号）： # 表示以…开始，match函数本身就从第一个开始匹配，匹配不成功就返回错误，所以不需要脱字符</li>
<li>$：表示以…结尾：将正常字符（非正则表达式特殊字符）规定到结尾的规则中来</li>
<li>|：匹配多个字符串或者表达式中的一个。</li>
<li>贪婪模式与非贪婪模式：贪婪模式匹配最长的满足条件的字符，非贪婪模式在后面加个？就只匹配满足条件的最短的结果</li>
</ul>
<p>举例：<br>4.1.<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"&lt;h1&gt;标题&lt;/h1&gt;"</span></span><br><span class="line">ret = re.match(<span class="string">'&lt;.+?&gt;'</span>,text) <span class="comment">#没有？匹配到&lt;h1&gt;标题&lt;/h1&gt;，有？匹配到&lt;h1&gt;</span></span><br><span class="line">print(ret.group())</span><br></pre></td></tr></table></figure></p>
<p>4.2. 匹配0-100之间的数字, 即不可以出现类似：09，101 1001<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"01"</span></span><br><span class="line">ret = re.match(<span class="string">'[1-9]\d?$|100$'</span>,text)</span><br><span class="line">print(ret.group())</span><br></pre></td></tr></table></figure></p>
<ol start="5">
<li>转移字符和原生字符串</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#encoding: utf-8</span></span><br><span class="line"><span class="keyword">import</span> re</span><br><span class="line"></span><br><span class="line"><span class="comment"># text = "apple price is $299"</span></span><br><span class="line"><span class="comment"># ret = re.search("\$\d+",text) #转义</span></span><br><span class="line"><span class="comment"># print(ret.group())</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># r = raw = 原生的</span></span><br><span class="line"><span class="comment"># text = r'\n'</span></span><br><span class="line"><span class="comment"># print(text)</span></span><br><span class="line"></span><br><span class="line">text = <span class="string">"\\n"</span>  <span class="comment">#= '\n'</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 1.转义</span></span><br><span class="line"><span class="comment"># python：'\\n' = \n</span></span><br><span class="line"><span class="comment"># \\\\n  -&gt;  \\n</span></span><br><span class="line"><span class="comment"># 正则表达式中：</span></span><br><span class="line"><span class="comment"># \\n  -&gt;  \n</span></span><br><span class="line"><span class="comment"># ret = re.match('\\\\n',text)</span></span><br><span class="line"><span class="comment"># 2. 原生</span></span><br><span class="line">ret = re.match(<span class="string">r'\\n'</span>,text)</span><br><span class="line">print(ret.group())</span><br></pre></td></tr></table></figure>
<h3 id="匹配函数"><a href="#匹配函数" class="headerlink" title="匹配函数"></a>匹配函数</h3><h4 id="match-和-search-函数"><a href="#match-和-search-函数" class="headerlink" title="match 和 search 函数"></a>match 和 search 函数</h4><ol>
<li>match:从开始的位置进行匹配。如果开始的位置没有匹配到。就直接失败了。如果想要匹配空白字符的数据，那么就要传入一个flag=re.DOTALL ,就可以匹配换行符了。（re.S=re.DOTALL）示例代码如下:</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line">text = <span class="string">"abc\nabc"</span></span><br><span class="line">ret = re.match(<span class="string">'abc.*abc'</span>, text,re.DOTALL)</span><br><span class="line">print(ret.group())</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>search:在字符串中找满足条件的字符。如果找到，就返回。说白了，就是只会找到第一个满足条件的。</li>
</ol>
<h4 id="group分组"><a href="#group分组" class="headerlink" title="group分组"></a>group分组</h4><p>  在正则表达式中，可以对过滤到的字符串进行分组。分组使用圆括号的方式。</p>
<ul>
<li>group :和group(e)是等价的,返回的是整个满足条件的字符串。</li>
<li>groups :返回的是里面的子组。索引从1开始。</li>
<li>group(1) :返回的是第一 个子组，可以传入多个。示例代码如下:</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">text = <span class="string">"apple's price $99,orange's price is $10"</span></span><br><span class="line">ret = re.search(<span class="string">'.*(\$\d+).*(\$\d+)'</span>,text)</span><br><span class="line">print(ret.group(<span class="number">0</span>)) <span class="comment"># 结果：apple's price $99,orange's price is $10</span></span><br><span class="line"><span class="comment"># ret.group(0) = ret.group()</span></span><br><span class="line">print(ret.group(<span class="number">1</span>)) <span class="comment"># 结果：$99</span></span><br><span class="line">print(ret.group(<span class="number">2</span>)) <span class="comment"># 结果：$10</span></span><br><span class="line"><span class="comment"># 把第一个第二个分组拿出来 ，以括号分组</span></span><br><span class="line">print(ret.group(<span class="number">1</span>,<span class="number">2</span>)) <span class="comment"># 结果： ('$99', '$10')</span></span><br><span class="line"><span class="comment"># 所有的子分组都拿出来，注意有s</span></span><br><span class="line">print(ret.groups()) <span class="comment"># # 结果： ('$99', '$10')</span></span><br></pre></td></tr></table></figure>
<h4 id="re模块常用函数"><a href="#re模块常用函数" class="headerlink" title="re模块常用函数"></a>re模块常用函数</h4><ol>
<li>findall函数：找出所有满足条件的，返回的是一个列表。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"apple's price $99,orange's price is $10"</span></span><br><span class="line">ret = re.findall(<span class="string">'\$\d+'</span>,text)</span><br><span class="line">print(ret) <span class="comment"># 结果：['$99','$10']</span></span><br></pre></td></tr></table></figure>
<ol start="2">
<li>sub函数：用来替换字符串，将匹配到字符串替换为其他字符。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"apple's price $99,orange's price is $10"</span></span><br><span class="line">ret = re.sub(<span class="string">'\$\d+'</span>,<span class="string">"0"</span>,text) <span class="comment"># sub函数的参数分别是(正则表达式，替换后的字符串，整个字符串，要代替几个（没有指明的话将代替所有满足条件的））</span></span><br><span class="line">print(ret) <span class="comment"># 结果：apple's price 0,orange's price is 0</span></span><br></pre></td></tr></table></figure>
<p>sub函数可以用作替换html标签，提取文本信息，例如拉勾网的职位招聘信息。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ret = re.sub(<span class="string">'&lt;.+?&gt;'</span>,<span class="string">""</span>,html) <span class="comment"># ？非贪婪模式</span></span><br></pre></td></tr></table></figure></p>
<ol start="3">
<li>split函数：使用正则表达式来分割字符串。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"hello&amp;world ni hao"</span></span><br><span class="line">ret = re.split(<span class="string">'[^a-zA-Z]'</span>,text)</span><br><span class="line">print(ret) <span class="comment"># 结果：['hello', 'world', 'ni', 'hao']</span></span><br></pre></td></tr></table></figure>
<ol start="4">
<li>compile函数：对于一些经常要用到的正则表达式，可以使用compile 进行编译，后期再使用的时候可以直接拿过来用，执行效率会更快。而且compile 还可以指定flag=re.VERBOSE，在写正则表达式的时候可以做好注释。</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">text = <span class="string">"the number is 20.50"</span></span><br><span class="line"><span class="comment"># r = re.compile('\d+\.?\d*')</span></span><br><span class="line">r = re.compile(<span class="string">r"""</span></span><br><span class="line"><span class="string">    \d+ # 小数点前面的数字</span></span><br><span class="line"><span class="string">    \.? # 小数点本身</span></span><br><span class="line"><span class="string">    \d* # 小数点后面的数字</span></span><br><span class="line"><span class="string">"""</span>,re.VERBOSE) <span class="comment"># 方便分段写注释</span></span><br><span class="line">ret = re.search(r,text)</span><br><span class="line">print(ret.group()) <span class="comment"># 结果：20.50</span></span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/beautifulsoup/" rel="tag"># beautifulsoup</a>
          
            <a href="/tags/xpath/" rel="tag"># xpath</a>
          
            <a href="/tags/正则表达式/" rel="tag"># 正则表达式</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/06/08/Python爬虫（1）/" rel="next" title="Python爬虫">
                <i class="fa fa-chevron-left"></i> Python爬虫
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/13/Python爬虫（3）/" rel="prev" title="Python爬虫（3）">
                Python爬虫（3） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#网络爬虫之数据提取"><span class="nav-number">1.</span> <span class="nav-text">网络爬虫之数据提取</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Xpath"><span class="nav-number">1.1.</span> <span class="nav-text">Xpath</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#XPath开发工具"><span class="nav-number">1.1.1.</span> <span class="nav-text">XPath开发工具</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#xpath语法"><span class="nav-number">1.1.2.</span> <span class="nav-text">xpath语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用方式："><span class="nav-number">1.1.3.</span> <span class="nav-text">使用方式：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#需要注意的知识点："><span class="nav-number">1.1.3.1.</span> <span class="nav-text">需要注意的知识点：</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#lxml解析器解析HTML代码"><span class="nav-number">1.2.</span> <span class="nav-text">lxml解析器解析HTML代码</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#安装lxml"><span class="nav-number">1.2.1.</span> <span class="nav-text">安装lxml</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用"><span class="nav-number">1.2.2.</span> <span class="nav-text">使用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#lxml结合xpath"><span class="nav-number">1.3.</span> <span class="nav-text">lxml结合xpath</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#BeautifulSoup"><span class="nav-number">1.4.</span> <span class="nav-text">BeautifulSoup</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#安装"><span class="nav-number">1.4.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用-1"><span class="nav-number">1.4.2.</span> <span class="nav-text">使用</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#find-all与find"><span class="nav-number">1.4.2.1.</span> <span class="nav-text">find_all与find</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#find-all的使用："><span class="nav-number">1.4.2.1.1.</span> <span class="nav-text">find_all的使用：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#find与find-all的区别："><span class="nav-number">1.4.2.1.2.</span> <span class="nav-text">find与find_all的区别：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#使用find和find-all的过滤条件："><span class="nav-number">1.4.2.1.3.</span> <span class="nav-text">使用find和find_all的过滤条件：</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取标签的属性："><span class="nav-number">1.4.2.2.</span> <span class="nav-text">获取标签的属性：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#string和strings、stripped-strings属性以及get-text方法："><span class="nav-number">1.4.2.3.</span> <span class="nav-text">string和strings、stripped_strings属性以及get_text方法：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#综合示例"><span class="nav-number">1.4.3.</span> <span class="nav-text">综合示例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#正则表达式"><span class="nav-number">1.5.</span> <span class="nav-text">正则表达式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#匹配规则"><span class="nav-number">1.5.1.</span> <span class="nav-text">匹配规则</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#特殊匹配字符"><span class="nav-number">1.5.1.1.</span> <span class="nav-text">特殊匹配字符</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#匹配函数"><span class="nav-number">1.5.2.</span> <span class="nav-text">匹配函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#match-和-search-函数"><span class="nav-number">1.5.2.1.</span> <span class="nav-text">match 和 search 函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#group分组"><span class="nav-number">1.5.2.2.</span> <span class="nav-text">group分组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#re模块常用函数"><span class="nav-number">1.5.2.3.</span> <span class="nav-text">re模块常用函数</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
